import { Component, OnInit, Inject, AfterViewChecked, ViewChild } from '@angular/core';
import { NgForm, FormControl } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA , MatDatepickerInputEvent } from '@angular/material';


import { Asset , AssetStatus, assetStatus, StatusNameMap } from '../../models/Asset';
import { AssetService } from '../../service/AssetService';
import { UserService } from '../../service/UserService';
import { Department } from '../../models/Department';
import { User } from '../../models/User';
import { Moment } from 'moment';
import * as moment from 'moment';
import {AssetType} from '../../models/AssetType';
import { environment } from '../../environments/environment';
import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
import { tap } from 'rxjs/operators';
@Component({
  templateUrl: './assetAdd.html',
  styleUrls: ['./assetAdd.css']
})
export class AssetAddComponent implements OnInit, AfterViewChecked {
  public hasBaseDropZoneOver: boolean;
  public hasAnotherDropZoneOver: boolean;
  uploader: FileUploader = new FileUploader({
    url: environment.apiUrl + 'api/fileupload/img',
    removeAfterUpload: true,
  });
  messages = {
    assetName: '',
    assetBrand: '',
    assetCode: '',
    assetPosition: ''
  };

  asset: Asset;
  departments: Department[];
  users: User[];
  assetStatus = assetStatus;
  StatusNameMap = StatusNameMap;
  assetTypes: AssetType[];
  assetUserId: string;
  isAdd: boolean;
  departmentUsers: User[];
  constructor(
    private dialogRef: MatDialogRef<AssetAddComponent>,
    private assetService: AssetService,
    private userService: UserService,
    @Inject(MAT_DIALOG_DATA) public data: {asset: Asset, departments: Department[], users: User[], assetTypes: AssetType[]}
   ) {
    this.asset = data.asset || { assetStatus: 0, assetType: '1010000', assetNum: 1 };
    this.asset.buyDateShow = new FormControl(moment(this.asset.buyDate));
    this.asset.buyDate = moment(this.asset.buyDate).toDate();
    this.departments = data.departments;
    this.users = data.users;
    this.assetTypes = data.assetTypes;
    this.assetUserId = this.asset.assetDepartmentId;
    if (data.asset) {
      this.isAdd = false;
    } else {
      this.isAdd = true;
    }
  }

  @ViewChild('assetForm')
  assetForm: NgForm;

  ngAfterViewChecked() {
    if (this.assetForm) {
      this.assetForm.valueChanges.subscribe(data => this.checkValidate());
    }
  }

  ngOnInit() {
    this.hasBaseDropZoneOver = false;
    this.hasAnotherDropZoneOver = false;
    this.onGetUsers().subscribe();
  }

  onGetUsers() {
    return this.userService.getUsers(1, 5, Number(this.assetUserId)).pipe(tap((res) => {
      this.departmentUsers = res.res;
    }))
  }

  onSelectDate( event: MatDatepickerInputEvent<Moment>) {
    this.asset.buyDate = event.value.toDate();
    this.asset.buyDateShow = new FormControl(event.value);
  }

  onSubmit() {
    this.checkValidate(true);
    if (this.assetForm.invalid) {
      // 触发mat的error
      this.assetForm.onSubmit(null);
      return false;
    }

    if (this.asset.id !== undefined) {
      this.assetService.update(this.asset).subscribe((res) => {
        this.dialogRef.close(res.res);
      });
    } else {
      this.assetService.create(this.asset).subscribe((res) => {
        this.dialogRef.close(res.res);
      });
    }
  }

  checkValidate(isSubmit?: boolean) {
    const form = this.assetForm;

    for (const field in AssetAddComponent.ErrorMessages) {

      const control = form.controls[field];

      if (control && control.valid) {
        this.messages[field] = '';
      }
      if (control && (control.dirty || isSubmit) && !control.valid) {
        const messages = AssetAddComponent.ErrorMessages[field];
        if (control.errors) {
          this.messages[field] = messages[Object.keys(control.errors)[0]];
        }
      }
    }
  }
  changeUser(assetUserId) {
    this.assetUserId = assetUserId;
    this.onGetUsers().subscribe();
  }
  selectedFileOnChanged(event:any) {
    this.upload();
  }

  upload() {
    this.uploader.queue.forEach(queue => {
      queue.withCredentials = false;
      queue.onError = (response: string, status: number) => {
        console.log(response, status);
      };

      queue.onSuccess = (responses, status, headers) => {
        if (status === 200) {
          const response = JSON.parse(responses);
          this.asset.assetImgUrl1 =  response['full-url'];
        } else {
          console.log('err', Error);
        }
      };

      queue.upload();
    });
  }
  static ErrorMessages = {
    assetName: {
      required: '设备名称不能为空'
    },
    assetBrand: {
      required: '设备品牌不能为空'
    },
    assetCode: {
      required: '设备编号不能为空'
    },
    assetPosition: {
      required: '座位号不能为空'
    }
  };
}
